package com.wangtao.rpc.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    public static void start(String hostname,int port) {
        start0(hostname, port);
    }

    public static void start0(String hostname,int port) {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);

        //创建服务器端的启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            bootstrap.group(bossGroup,workerGroup)  //设置两个线程组
                    .channel(NioServerSocketChannel.class)  //用NioServerSocketChannel作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG,128) //设置线程队列等待连接的个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true) //设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {    //给workerGrroup的EventLoop设置对应的管道处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder()); //添加解码器
                            pipeline.addLast(new StringEncoder()); //添加编码器
                            pipeline.addLast(new NettyServerHandler()); //添加自定义Handler,业务全在这里面
                        }
                    });

            //绑定端口进行异步监听
            ChannelFuture future = bootstrap.bind(hostname, port).addListener(cf -> {
                if (cf.isSuccess()) {
                    System.out.println("服务端:" + hostname + ":" + port + "启动成功");
                } else {
                    System.out.println("服务端启动失败");
                }
            });

            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
